

    const filesystemService = require('../service/filesystemService')
    const passport = require('koa-passport')
    const encryption = require('../lib/encryption')
    const fs = require('fs')

    module.exports = {

        userdata: async (ctx, next) => {
            await ctx.render('userdata', {
                username: ctx.state.user.username
            })
        },

        login: async (ctx, next) => {
            await ctx.render('login', {})
        },

        checklogin: async (ctx, next) => {
            // // 使用ctx.request.body方法获取数据（koa-bodyparser）
            // const {username,password} = ctx.request.body;
            // ctx.session.username = username;
            // ctx.session.password = password;
            // console.log(ctx.request.query);
            // let user = await filesystemService.checkUser(username, password);
            // if(user) {
            //     ctx.redirect('/filesystem/');
            // }
            // else {
            //     await ctx.render('login', {
            //         info: '账号密码错误'
            //     });
            // }

            // 使用passport
            return passport.authenticate('local', async (err, user, info) => {
                if(err) {
                    ctx.session.errorMsg = 'passport 本地验证错误'
                    ctx.response.redirect('/filesystem/error')
                }
                if(!user) {
                    ctx.session.logInfo = '账号密码错误'
                    ctx.response.redirect('/filesystem/login')
                }
                else {
                    let token = encryption.getUserToken(user)
                    ctx.session.token = token
                    ctx.login(user)
                    ctx.response.redirect('/filesystem/')
                }
            }) (ctx, next)
        },

        logout: async (ctx, next) => {
            ctx.logout()
            ctx.redirect('/filesystem/login');
        },

        file: async (ctx, next) => {
            // let documentRoot = "D:/web/apache/htdocs/tp5";
            let documentRoot = "C:/Users/zhai/Desktop/实验项目";
            let currentroot = "";
            let resinfo = {};
            // 对请求字符串进行处理 获取请求数据
            // ctx.request.url 可以获取当前路由下的请求
            // ctx.request.url= 可以重写路由
            if(ctx.request.url.indexOf("?")!=-1) {
                let resarr1 = ctx.request.url.split("?")[1];
                let resarr2 = resarr1.split("&");
                for(let i=0;i<resarr2.length;i++) {
                    let info = resarr2[i].split("=");
                    // 对象创建属性和赋值
                    resinfo[info[0]] = info[1];
                }
                currentroot = resinfo.reqFileurl;
                console.log(currentroot);
                // 获取数据后 重写url 重新渲染页面
                ctx.request.url = '/filesystem/file';
            }
            let fileData = await new Promise(resolve => { 
                // 存储当前页面的文件信息
                let fileData = {
                    upPath: '',
                    currentPath: '',
                    nextPath: [],
                    filesname: [],
                    isDir: []
                }
                fs.readdir(`${documentRoot}${currentroot}`, (err, files) => {
                    if(err) ctx.body = '读取错误';
                    fileData.upPath = resinfo.upPath;
                    fileData.currentPath = currentroot;
                    for(let i=0;i<files.length;i++) {
                        fileData.filesname.push(files[i]);
                        fileData.nextPath.push(`${currentroot}/${files[i]}`);
                        // 判断类型 文件夹or文件
                        if(fs.statSync(`${documentRoot}${fileData.nextPath[i]}`).isDirectory()) fileData.isDir.push(true);
                        else fileData.isDir.push(false);
                    }
                    resolve(fileData);
                });
            });
            await ctx.render('filesystem', {
                fileData: fileData
            });
        },

        role: async (ctx, next) => {
            let roleinfo = await filesystemService.getRoleInfo()
            let showData = await filesystemService.showUserdata()
            await ctx.render('role', {
                roleinfo: roleinfo,
                showData: showData
            });
        },

        rolesearch: async (ctx, next) => {
            let roleinfo = await filesystemService.getRoleInfo()
            const {username, phone, roleid} = ctx.request.body
            const searchInfo = {
                username: username,
                phone: phone,
                roleid: roleid
            }
            let searchResult = await filesystemService.searchUserData(searchInfo)
            await ctx.render('search', {
                roleinfo: roleinfo,
                searchResult: searchResult
            })
        },

        addUserPage: async (ctx, next) => {
            let roleinfo = await filesystemService.getRoleInfo()
            await ctx.render('addUser', {
                roleinfo: roleinfo
            })
        },

        addUser: async (ctx, next) => {
            let roleinfo = await filesystemService.getRoleInfo()
            const {username, phone, password, roleid} = ctx.request.body
            let res = await filesystemService.addUser(username, phone, password, roleid)
            await ctx.render('addUser', {
                roleinfo: roleinfo,
                res: res ? '新增成功！' : '新增失败！'    
            })
        },

        deleteUser: async (ctx, next) => {
            const {username} = ctx.request.query
            await filesystemService.deleteUser(username)
            ctx.response.redirect('/filesystem/role')
        },

        error: async (ctx, next) => {
            await ctx.render('error', {
                message: ctx.session.errorMsg
            })
        }

    }